package com.enation.app.javashop.manager.api.member;

import com.enation.app.javashop.core.base.context.Region;
import com.enation.app.javashop.core.base.context.RegionFormat;
import com.enation.app.javashop.core.base.model.vo.SuccessMessage;
import com.enation.app.javashop.core.distribution.exception.DistributionException;
import com.enation.app.javashop.core.member.model.dos.LeaderDO;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.model.dto.AuditLeaderDTO;
import com.enation.app.javashop.core.member.model.vo.LeaderQueryVO;
import com.enation.app.javashop.core.member.model.vo.LeaderVO;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.system.sendMessage.WechatSendMessage;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/members/leader")
@Api(description = "团长管理相关API")
public class LeaderManagerController {

    @Autowired
    private LeaderManager leaderManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private WechatSendMessage wechatSendMessage;
    protected final Log logger = LogFactory.getLog(this.getClass());

    @ApiOperation(value = "根据id查看团长详情", response = LeaderDO.class)
    @GetMapping(value = "/get/{leader_id}")
    public Map<String, Object> getById(@PathVariable("leader_id") Integer leaderId){
        LeaderDO leaderDO = this.leaderManager.getById(leaderId);

        Integer memberId = leaderDO.getMemberId();
        Member member = null;
        if(memberId != null){
            member = memberManager.getModel(leaderDO.getMemberId());
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("leader", leaderDO);
        resultMap.put("member", member);
        return resultMap;
    }


    @ApiOperation(value = "添加团长")
    @PostMapping(value = "add_leader")
    public void addLeader(LeaderVO leaderVO, @RegionFormat @RequestParam(value = "region") Region region){
        LeaderDO leaderDO = new LeaderDO();
        BeanUtil.copyProperties(leaderVO, leaderDO);

        Member member = memberManager.getModel(leaderDO.getMemberId());
        if(member == null){
            throw new RuntimeException("会员不存在");
        }
        member.setRealName(leaderVO.getLeaderName());
        member.setMidentity(leaderVO.getMidentity());
        memberManager.edit(member, member.getMemberId());

        // 添加团长
        leaderDO.setLeaderMobile(member.getMobile());
        leaderDO.setProvince(region.getProvince());
        leaderDO.setCity(region.getCity());
        leaderDO.setCounty(region.getCounty());
        leaderDO.setTown(region.getTown());
        leaderDO.setProvinceId(region.getProvinceId());
        leaderDO.setCityId(region.getCityId());
        leaderDO.setCountyId(region.getCountyId());
        leaderDO.setTownId(region.getTownId());
        leaderDO.setOpStatus(1);
        leaderDO.setSourceFrom(1);
        leaderDO.setCreaterName("管理员");
        leaderDO.setAuditStatus(2);

        leaderManager.addLeader(leaderDO);
    }


    @PostMapping(value = "/update_pick_up_site")
    @ApiOperation("修改自提点信息")
    public void updateLeader(LeaderVO leaderVO, @RegionFormat @RequestParam(value = "region") Region region){
        LeaderDO leaderDO = new LeaderDO();
        BeanUtil.copyProperties(leaderVO,leaderDO);
        if(region != null){
            leaderDO.setProvinceId(region.getProvinceId());
            leaderDO.setProvince(region.getProvince());
            leaderDO.setCityId(region.getCityId());
            leaderDO.setCity(region.getCity());
            leaderDO.setCountyId(region.getCountyId());
            leaderDO.setCounty(region.getCounty());
            leaderDO.setTownId(region.getTownId());
            leaderDO.setTown(region.getTown());
            leaderDO.setLat(region.getShopLat());
            leaderDO.setLng(region.getShopLng());
        }
        leaderManager.edit(leaderDO,leaderDO.getLeaderId());
    }


    @ApiOperation(value = "查询团长列表", response = LeaderDO.class)
    @GetMapping(value = "list")
    public Page list(LeaderQueryVO leaderQueryVO, @RegionFormat @RequestParam(value = "region", required = false) Region region){
        if(region != null){
            leaderQueryVO.setProvinceId(region.getProvinceId());
            leaderQueryVO.setCityId(region.getCityId());
            leaderQueryVO.setCountyId(region.getCountyId());
            leaderQueryVO.setTownId(region.getTownId());
        }
        return this.leaderManager.list(leaderQueryVO);
    }


    @ApiOperation(value = "删除团长")
    @DeleteMapping(value = "/{leader_id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "leader_id", value = "团长id", required = true, dataType = "int", paramType = "path")
    })
    public boolean delete(@ApiIgnore @PathVariable("leader_id") Integer leaderId){
        return this.leaderManager.delete(leaderId);
    }


    @PostMapping(value = "/audit")
    @ApiOperation("审核团长")
    public SuccessMessage audit(@RequestBody AuditLeaderDTO auditDTO) {
        try {
            Integer auditStatus = auditDTO.getAuditStatus();
            LeaderDO leaderDO = leaderManager.getById(auditDTO.getId());
            leaderDO.setLeaderType(auditDTO.getLeaderType());
            leaderDO.setAuditStatus(auditStatus);
            leaderDO.setAuditRemark(auditDTO.getAuditRemark());
            leaderDO.setOperateAreas(auditDTO.getOperateAreas());
            leaderDO.setAuditTime(DateUtil.getDateline());
            leaderDO.setDispatchType(auditDTO.getDispatchType());
            leaderDO.setShipPriority(auditDTO.getShipPriority());
            leaderManager.edit(leaderDO, leaderDO.getLeaderId());
            //推送自提点审核通知消息
            try {
                wechatSendMessage.sendPickUpPointMessage(leaderDO);
            }catch (Exception e){
                logger.error("发送自提点审核记录：", e);
            }

            return new SuccessMessage("审核成功");
        } catch (Exception e) {
            logger.error("审核团长出错", e);
            throw new DistributionException("-1", "审核团长出错" + e.getMessage());
        }
    }


    @PostMapping(value = "/openOrClose")
    @ApiOperation("启用或禁用")
    public SuccessMessage openOrClose(String leaderIds, Integer status) {
        try {
            leaderManager.updateLeaderStatus(leaderIds,status);
            return new SuccessMessage("操作成功");
        } catch (Exception e) {
            logger.error("启用或禁用出错", e);
            throw new DistributionException("-1", "启用或禁用出错" + e.getMessage());
        }
    }

    @PostMapping(value = "/updatePriority/{leader_id}/{ship_priority}")
    @ApiOperation("更新团长优先级")
    public Boolean updatePriority(@PathVariable("leader_id") Integer leaderId,@PathVariable("ship_priority")  Integer shipPriority) {
        leaderManager.updatePriority(leaderId,shipPriority);
       return true;
    }
}
